package org.samoji.GUI;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import org.samoji.model.Database;

@SuppressWarnings("serial")
public class InsertNew extends JFrame {
	private JButton _btnSubmit;
	private JTextField[] _fields;
	
	
	public InsertNew(final String tableName) throws SQLException {
		super();
		setTitle("New " + tableName);
		setLayout(new GridLayout(0, 2));
		
		String sql = "SELECT * FROM " + tableName;
		PreparedStatement pst = Database.getInstance().getConnection().prepareStatement(sql);
		final ResultSetMetaData rsm = pst.executeQuery().getMetaData();
		
		int totalFlds = rsm.getColumnCount();
		_fields = new JTextField[totalFlds];
		
		// _fields = new HashMap<String, JTextField>();
		for(int i = 1; i <= rsm.getColumnCount(); i++) {
			add(new JLabel(rsm.getColumnLabel(i)));
			_fields[i-1] = new JTextField();
			add(_fields[i-1]);
			// _fields.put(rsm.getColumnLabel(i), new JTextField());
			// add(_fields.get(rsm.getColumnLabel(i)));
			
			System.out.println(rsm.getColumnLabel(i) + " : " + rsm.getColumnType(i) + " : " + rsm.getColumnTypeName(i));
			
		}
		
		_btnSubmit = new JButton("Submit");
		
		_btnSubmit.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				StringBuffer sql = new StringBuffer("INSERT INTO " + tableName + " VALUES (?");
				
				try {
					for(int i = 1; i < rsm.getColumnCount(); i++) {
						sql.append(", ?");
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				sql.append(")");
				
				System.out.println("SQL: " + sql.toString());
				//TODO: si potrebbe salvare il tipo di dato SQL insieme al valore
				try {
					PreparedStatement pst = Database.getInstance().getConnection().prepareStatement(sql.toString());
					
					int selectedElement = 1;
					JTextField fldTemp;
					
					for(int i = 1; i <= rsm.getColumnCount(); i++) {
						fldTemp = _fields[i-1];
						
						switch(rsm.getColumnType(i)) {
							case Types.NUMERIC:
								pst.setInt(selectedElement, Integer.parseInt(fldTemp.getText().toString().trim()));
								break;
							
							case Types.VARCHAR:
								pst.setString(selectedElement, fldTemp.getText().toString().trim());
								break;
						}
						
						selectedElement++;	
					}
					
					pst.executeQuery();
					
					JOptionPane.showMessageDialog(null, "Nuovo " + tableName + " inserito con successo", "Inserimento riuscito", JOptionPane.INFORMATION_MESSAGE);
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		});
		
		add(_btnSubmit);
		pack();
	}
}